package com.lezheba.action;

import java.util.Date;

import org.apache.log4j.Logger;

import com.lezheba.db.entity.User;
import com.lezheba.service.UserAdminService;

public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 1012329652723613183L;
	static Logger logger = Logger.getLogger(LoginAction.class.getName());

	private UserAdminService service = new UserAdminService();

	private String email;
	private String password;
	private Date childBirth;
	private String confirmPassword;
	private User user;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public LoginAction() {
	}

	public String login() throws Exception {
		System.out.println(email);
		System.out.println(password);
		int tag = 0;
		if (!service.isExist(email)) {
			tag = -1; // email not exist
		} else {
			User user = service.get(email, password);
			if (user == null) {
				tag = -2; // password is not correct
			} else {
				super.putSession(USER, email);
			}

		}

		return super.ajax(tag);

	}
	
  
	public String execute()  {
		email = super.getSession(USER);
		if (email != null) {
			 user = service.get(email);
		}
		return SUCCESS;
	}
	
	public String logout() throws Exception {
		super.removeSession("user" );
		return super.ajax(0);

	}

	public String register() throws Exception {
		System.out.println(email);
		System.out.println(password);
		System.out.println(confirmPassword);
		System.out.println(childBirth);
		int tag = 0;
		if (email != null && password != null && confirmPassword != null) {
			if (!password.equals(confirmPassword)) {
				tag = -11; // password not match
			} else if (service.isExist(email)) {
				tag = -12; // email exist
			} else {
				service.addUser(email, password, childBirth);
				super.putSession("user", email);
				super.putSession("password", password);
			}
		} else {
			tag = -1;
		}

		return super.ajax(tag);

	}

	public Date getChildBirth() {
		return childBirth;
	}

	public void setChildBirth(Date childBirth) {
		this.childBirth = childBirth;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
